<?php
/**
 * ===============================================
 * 版权所有 2019-2050 青岛铁锤科技有限公司，并保留所有权利。
 * 网站地址: http://www.huaxianling.com
 * ===============================================
 * Author: Happy dong
 * Created Time: 2019-07-03 09:45
 *
 * Version: 2.0
 */

namespace App\Modules\Employee\Repositories;


use App\Exceptions\NotFoundException;
use App\Models\UserPortfolio;
use App\Modules\Employee\Criterias\GetAppointmentBgCriteria;
use App\Modules\Employee\Criterias\getNewPortfolioListCriteria;
use App\Modules\Employee\Criterias\GetPortfolioCriteria;
use App\Modules\Employee\Criterias\GetWxPortfolioListCriteria;
use App\Modules\Employee\Validators\PortfolioValidator;
use Flower\Core\Repository\Eloquent\BaseRepository;
use Illuminate\Support\Facades\DB;

class PortfolioRepository extends BaseRepository
{
	public function model()
	{	
		return UserPortfolio::class;
	}

	public function validator()
	{
		return PortfolioValidator::class;
	}

	public function setInc($requestData){

		return $this->model->where(['id'=>$requestData['portfolio_id']])->increment('play_times');
	}

	/**
	 * 获取作品集详情页面内容
	 * @param $ids
	 * @return mixed
	 * @throws \Flower\Core\Repository\Exceptions\RepositoryException
	 */
	public function getAppointmentBgById($ids){
		$res =  $this->pushCriteria(new GetAppointmentBgCriteria())->find($ids);
		if(!empty($res->resource)) $res->resource->video;
		if(!empty($res->user)) $res->user->picture;
		return $res;
	}

	/**
	 * 新增作品集
	 * @param $barberId
	 * @param $name
	 * @param $serviceId
	 * @param $desc
	 * @return mixed
	 */
	public function addPortfolio($barberId,$name,$serviceId,$desc,$storeId){
		$params = [
			'user_id' =>$barberId,
			'name'=>$name,
			'service_id'=>$serviceId,
			'desc'=>$desc,
			'store_id' =>$storeId,
		];
		return $this->create($params);
	}

	/**
	 * 验证是否存在
	 * @param $portfolioId
	 * @return mixed
	 * @throws NotFoundException
	 */
	public function isExisted($portfolioId){
		$info = $this->find($portfolioId);
		if(empty($info)){
			throw new NotFoundException(['msg'=>'该作品集不存在']);
		}
		return $info;
	}

	public function editPortfolio($portfolioId,$barberId,$name,$serviceId,$desc,$storeId){
		$params = [
			'user_id' =>$barberId,
			'name'=>$name,
			'service_id'=>$serviceId,
			'desc'=>$desc,
			'store_id' =>$storeId,
		];
		return $this->update($params,$portfolioId);
	}

	/**
	 * @param int $storeId
	 * @param int $barberId
	 * @param int $pageSize
	 * @param string $serviceName
	 * @return mixed
	 * @throws \Flower\Core\Repository\Exceptions\RepositoryException
	 */
	public function getListByUserIdAndBarberId($storeId=0,$barberId=0,$pageSize=10,$protfolioName=null,$memberId=0,$portfolio_id=0){
		$list = $this->pushCriteria(new GetWxPortfolioListCriteria($storeId,$barberId,$protfolioName,$memberId,$portfolio_id))->paginate($pageSize, ['*'], 'paginate');
//		dd($list);
		return $list;
	}

	/**
	 * 作品集经营数据
	 * @param $storeId
	 * @param $date
	 * @param $compareDate
	 * @return array
	 */
	public function getAmountRate($storeId,$date,$compareDate){
		$list = DB::table('user_portfolio')
			->selectRaw('date(created_at) as dates, count(id) as counts')
			->whereRaw('(store_id=' . $storeId . ' and date(created_at)="' . $date . '")')
			->orWhereRaw('(store_id=' . $storeId . ' and date(created_at)="' . $compareDate . '")')
			->groupBy('dates')
		    ->whereNull('deleted_at')
			->get()
			->toArray();
		$list = array_map(function ($v){
			return [
				'dates' => $v->dates,
				'counts' => $v->counts
			];
		},$list);
		return $list;
	}

    //获取理发师在某店某一日期昨天作品数
    public function getBarberDatePortfolioNum($user_id, $store_id, $date)
    {

        return $this->model->where('user_id', $user_id)
            ->where('store_id', $store_id)
            ->whereDate('created_at','=',$date)
            ->get()
            ->count();
    }

    //根据获取作品集
    public function getPortfolioById($portfolio_id)
    {
        $select = [
            'hx_user_portfolio.id',
            'hx_user_portfolio.user_id',
            'hx_user_portfolio.name',
            'hx_user_portfolio.desc',
            'hx_video.thumb as image'
        ];
        $select = implode($select,',');
        return $this
            ->model
            ->selectRaw($select)
            ->leftJoin('user_portfolio_resource','user_portfolio.id','user_portfolio_resource.portfolio_id')
            ->leftJoin('video','user_portfolio_resource.resource_id','video.id')
            ->where('user_portfolio.id',$portfolio_id)
            ->first();
    }


    /**
     * 作品集查询
     * @param $storeId
     * @param $startDate
     * @param $endDate
     * @return mixed
     */
    public function getOrderRankListByBarberId($storeId,$startDate,$endDate){
	$sql = 'select m.barber_id,m.barber_name,m.username,count(p.id) as counts  from (SELECT distinct u.id AS barber_id, u.nick AS barber_name, u.username as username FROM hx_user AS u LEFT JOIN hx_user_store AS s ON u.id = s.uid	 WHERE s.sid = "'.$storeId.'") as m LEFT JOIN hx_user_portfolio AS p ON m.barber_id = p.user_id  AND DATE_FORMAT(p.created_at, \'%Y-%m-%d\') <= "'.$startDate.'" and DATE_FORMAT(p.created_at,\'%Y-%m-%d\') >="'.$endDate.'" GROUP BY m.barber_id order by counts desc';

    	return DB::select($sql);
    }

    /**
     * 根据服务id获取其关联作品数
     * @param $service_id
     * @return mixed
     */
    public function getCountByService($service_id)
    {
        return $this->model->where('service_id',$service_id)->count();
    }


	/**
	 * 通过作品预约订单成功数 自动增加1
	 * @param $portfolioId
	 * @return mixed
	 */
    public function updateOrderNum($portfolioId){
       return $this->model->where('id',$portfolioId)->increment('order_num',1);
    }

	/**
	 * 播放次数
	 * @param $portfolioId
	 * @return mixed
	 */
    public function getPlayTimes($portfolioId){
    	return $this->model->where('id',$portfolioId)->value('play_times');
    }
}
